import React, { useState, useEffect } from 'react';
import { Table, Button, Space, Modal, Form, Input, message, Tag, Select, InputNumber } from 'antd';
import { EyeOutlined, TruckOutlined, EditOutlined, CloseOutlined } from '@ant-design/icons';
import { OrderApi, OrderVO, OrderDeliveryVO } from '../../../api/mall/order';

const { Option } = Select;
const { TextArea } = Input;

const MallOrder: React.FC = () => {
  const [orders, setOrders] = useState<OrderVO[]>([]);
  const [loading, setLoading] = useState(false);
  const [deliveryModalVisible, setDeliveryModalVisible] = useState(false);
  const [remarkModalVisible, setRemarkModalVisible] = useState(false);
  const [priceModalVisible, setPriceModalVisible] = useState(false);
  const [currentOrder, setCurrentOrder] = useState<OrderVO | null>(null);
  const [deliveryForm] = Form.useForm();
  const [remarkForm] = Form.useForm();
  const [priceForm] = Form.useForm();

  // 获取订单列表
  const fetchOrders = async () => {
    setLoading(true);
    try {
      const response = await OrderApi.getOrderPage({});
      setOrders(response.data?.list || []);
    } catch (error) {
      message.error('获取订单列表失败');
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchOrders();
  }, []);

  // 订单发货
  const handleDelivery = async (values: any) => {
    if (!currentOrder) return;
    
    try {
      await OrderApi.deliveryOrder({
        id: currentOrder.id!,
        logisticsId: values.logisticsId,
        logisticsNo: values.logisticsNo,
      });
      message.success('发货成功');
      setDeliveryModalVisible(false);
      setCurrentOrder(null);
      deliveryForm.resetFields();
      fetchOrders();
    } catch (error) {
      message.error('发货失败');
    }
  };

  // 更新订单备注
  const handleUpdateRemark = async (values: any) => {
    if (!currentOrder) return;
    
    try {
      await OrderApi.updateOrderRemark(currentOrder.id!, values.remark);
      message.success('更新备注成功');
      setRemarkModalVisible(false);
      setCurrentOrder(null);
      remarkForm.resetFields();
      fetchOrders();
    } catch (error) {
      message.error('更新备注失败');
    }
  };

  // 调整订单价格
  const handleUpdatePrice = async (values: any) => {
    if (!currentOrder) return;
    
    try {
      await OrderApi.updateOrderPrice(currentOrder.id!, values.price);
      message.success('调整价格成功');
      setPriceModalVisible(false);
      setCurrentOrder(null);
      priceForm.resetFields();
      fetchOrders();
    } catch (error) {
      message.error('调整价格失败');
    }
  };

  // 关闭订单
  const handleCloseOrder = async (id: number) => {
    try {
      await OrderApi.closeOrder(id);
      message.success('关闭订单成功');
      fetchOrders();
    } catch (error) {
      message.error('关闭订单失败');
    }
  };

  // 打开发货模态框
  const openDeliveryModal = (order: OrderVO) => {
    setCurrentOrder(order);
    setDeliveryModalVisible(true);
  };

  // 打开备注模态框
  const openRemarkModal = (order: OrderVO) => {
    setCurrentOrder(order);
    remarkForm.setFieldsValue({ remark: order.remark });
    setRemarkModalVisible(true);
  };

  // 打开价格调整模态框
  const openPriceModal = (order: OrderVO) => {
    setCurrentOrder(order);
    priceForm.setFieldsValue({ price: order.payPrice });
    setPriceModalVisible(true);
  };

  const getStatusTag = (status: number) => {
    const statusMap: Record<number, { color: string; text: string }> = {
      0: { color: 'orange', text: '待付款' },
      10: { color: 'blue', text: '待发货' },
      20: { color: 'cyan', text: '待收货' },
      30: { color: 'green', text: '已完成' },
      40: { color: 'red', text: '已取消' },
      50: { color: 'purple', text: '售后中' }
    };
    const statusInfo = statusMap[status] || { color: 'default', text: '未知' };
    return <Tag color={statusInfo.color}>{statusInfo.text}</Tag>;
  };

  const columns = [
    {
      title: '订单号',
      dataIndex: 'no',
      key: 'no',
      width: 180,
    },
    {
      title: '收货人',
      dataIndex: 'receiverName',
      key: 'receiverName',
    },
    {
      title: '手机号',
      dataIndex: 'receiverMobile',
      key: 'receiverMobile',
    },
    {
      title: '商品数量',
      dataIndex: 'productCount',
      key: 'productCount',
    },
    {
      title: '订单金额',
      dataIndex: 'payPrice',
      key: 'payPrice',
      render: (price: number) => `¥${(price / 100).toFixed(2)}`,
    },
    {
      title: '订单状态',
      dataIndex: 'status',
      key: 'status',
      render: (status: number) => getStatusTag(status),
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      key: 'createTime',
    },
    {
      title: '操作',
      key: 'action',
      width: 300,
      render: (_: any, record: OrderVO) => (
        <Space size="small" wrap>
          <Button
            type="link"
            icon={<EyeOutlined />}
            size="small"
          >
            查看
          </Button>
          {record.status === 10 && (
            <Button
              type="link"
              icon={<TruckOutlined />}
              onClick={() => openDeliveryModal(record)}
              size="small"
            >
              发货
            </Button>
          )}
          <Button
            type="link"
            icon={<EditOutlined />}
            onClick={() => openRemarkModal(record)}
            size="small"
          >
            备注
          </Button>
          <Button
            type="link"
            onClick={() => openPriceModal(record)}
            size="small"
          >
            调价
          </Button>
          {[0, 10].includes(record.status) && (
            <Button
              type="link"
              danger
              icon={<CloseOutlined />}
              onClick={() => handleCloseOrder(record.id!)}
              size="small"
            >
              关闭
            </Button>
          )}
        </Space>
      ),
    },
  ];

  return (
    <div style={{ padding: '24px' }}>
      <Table
        columns={columns}
        dataSource={orders}
        rowKey="id"
        loading={loading}
        scroll={{ x: 1200 }}
        pagination={{
          showSizeChanger: true,
          showQuickJumper: true,
          showTotal: (total) => `共 ${total} 条记录`,
        }}
      />

      {/* 发货模态框 */}
      <Modal
        title="订单发货"
        open={deliveryModalVisible}
        onCancel={() => {
          setDeliveryModalVisible(false);
          setCurrentOrder(null);
          deliveryForm.resetFields();
        }}
        onOk={() => deliveryForm.submit()}
        destroyOnClose
      >
        <Form
          form={deliveryForm}
          layout="vertical"
          onFinish={handleDelivery}
        >
          <Form.Item
            name="logisticsId"
            label="物流公司"
            rules={[{ required: true, message: '请选择物流公司' }]}
          >
            <Select placeholder="请选择物流公司">
              <Option value={1}>顺丰快递</Option>
              <Option value={2}>圆通快递</Option>
              <Option value={3}>中通快递</Option>
              <Option value={4}>韵达快递</Option>
              <Option value={5}>申通快递</Option>
            </Select>
          </Form.Item>
          <Form.Item
            name="logisticsNo"
            label="物流单号"
            rules={[{ required: true, message: '请输入物流单号' }]}
          >
            <Input placeholder="请输入物流单号" />
          </Form.Item>
        </Form>
      </Modal>

      {/* 备注模态框 */}
      <Modal
        title="订单备注"
        open={remarkModalVisible}
        onCancel={() => {
          setRemarkModalVisible(false);
          setCurrentOrder(null);
          remarkForm.resetFields();
        }}
        onOk={() => remarkForm.submit()}
        destroyOnClose
      >
        <Form
          form={remarkForm}
          layout="vertical"
          onFinish={handleUpdateRemark}
        >
          <Form.Item
            name="remark"
            label="备注内容"
          >
            <TextArea placeholder="请输入备注内容" rows={4} />
          </Form.Item>
        </Form>
      </Modal>

      {/* 价格调整模态框 */}
      <Modal
        title="调整订单价格"
        open={priceModalVisible}
        onCancel={() => {
          setPriceModalVisible(false);
          setCurrentOrder(null);
          priceForm.resetFields();
        }}
        onOk={() => priceForm.submit()}
        destroyOnClose
      >
        <Form
          form={priceForm}
          layout="vertical"
          onFinish={handleUpdatePrice}
        >
          <Form.Item
            name="price"
            label="订单价格（分）"
            rules={[{ required: true, message: '请输入订单价格' }]}
          >
            <InputNumber
              placeholder="请输入订单价格"
              style={{ width: '100%' }}
              min={0}
            />
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
};

export default MallOrder;